using ES3Internal;

namespace WooEngine.Persistence.Provider
{

    public class EasySaveProvider : IDBProvider
    {
        private string m_tag;
        private ES3Settings m_es3settings;
        private bool m_isAutoSync;

        public string Tag => m_tag;

        public bool IsHasDB => m_es3settings != null && ES3IO.FileExists(m_es3settings.FullPath);

        public EasySaveProvider(string tag, string password, bool isAutoSync)
        {
            m_tag = tag;
            m_isAutoSync = isAutoSync;
            m_es3settings = new ES3Settings(tag);

            m_es3settings.directory = ES3.Directory.PersistentDataPath;

#if DB_ENCRYPT
        m_es3settings.encryptionType = ES3.EncryptionType.AES;
        m_es3settings.encryptionPassword = password;
        m_es3settings.compressionType = ES3.CompressionType.Gzip;
#endif
            m_es3settings.location = ES3.Location.Cache;
            ES3.CacheFile(m_es3settings);
        }

        public void DeleteDB()
        {
            if (IsHasDB)
            {
                ES3.DeleteFile(m_es3settings);
            }
        }

        public bool IsHasKey(string key)
        {
            return ES3.KeyExists(key, m_tag);
        }

        public T Load<T>(string key)
        {
            return ES3.Load<T>(key, m_tag);
        }

        public void Save<T>(string key, T data)
        {
            ES3.Save<T>(key, data, m_tag);
            if (m_isAutoSync)
            {
                sync();
            }
        }

        public void Delete(string key)
        {
            ES3.DeleteKey(key, m_tag);
        }

        public void Release()
        {
            m_tag = null;
            m_es3settings = null;
        }

        public void sync()
        {
            ES3.StoreCachedFile(m_es3settings);
        }
    }
}